package com.example.pcbcsmbackend.service;

import com.example.pcbcsmbackend.entity.Category;
import com.example.pcbcsmbackend.repository.CategoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
public class CategoryService {
    
    @Autowired
    private CategoryRepository categoryRepository;
    
    // 添加分类
    public Category addCategory(String categoryName, Integer parentId, String description) {
        Category category = new Category(categoryName, parentId, description);
        return categoryRepository.save(category);
    }
    
    // 获取所有分类
    public List<Category> getAllCategories() {
        return categoryRepository.findAll();
    }
    
    // 获取顶级分类
    public List<Category> getTopLevelCategories() {
        return categoryRepository.findByParentIdIsNull();
    }
    
    // 根据父分类获取子分类
    public List<Category> getCategoriesByParent(Integer parentId) {
        return categoryRepository.findByParentId(parentId);
    }
    
    // 根据ID查找分类
    public Optional<Category> findById(Integer categoryId) {
        return categoryRepository.findById(categoryId);
    }
    
    // 更新分类
    public Category updateCategory(Category category) {
        category.setUpdatedAt(LocalDateTime.now());
        return categoryRepository.save(category);
    }
    
    // 删除分类
    public void deleteCategory(Integer categoryId) {
        categoryRepository.deleteById(categoryId);
    }
    
    // 批量删除分类
    @Transactional
    public void batchDeleteCategories(List<Integer> categoryIds) {
        categoryRepository.deleteAllById(categoryIds);
    }
} 